<template>
  <div id="user-login">
    <h2 class="title">云协同文档 - 用户登录</h2>
    <div class="description">企业级智能云协同文档系统</div>
    <a-form :model="formState" autoComplete="off" @finish="handleSubmit">
      <a-form-item name="username" :rules="{ required: true, message: '请输入用户名' }">
        <a-input v-model:value="formState.username" placeholder="请输入用户名" />
      </a-form-item>
      <a-form-item name="password" :rules="{ required: true, message: '请输入密码' }">
        <a-input-password v-model:value="formState.password" placeholder="请输入密码" />
      </a-form-item>
      <div class="tips">
        没有账号？
        <RouterLink to="/user/register">点我注册</RouterLink>
      </div>
      <a-form-item>
        <a-button type="primary" html-type="submit" style="width: 100%">登录</a-button>
      </a-form-item>
    </a-form>
  </div>
</template>
<script lang="ts" setup>
import { reactive } from 'vue'
import { loginApi } from '@/api/UserApi.ts'
import { useUserStore } from '@/stores/userStore.ts'
import { message } from 'ant-design-vue'
import router from '@/router'

const formState = reactive<any>({
  username: '',
  password: '',
})

const userStore = useUserStore()

/**
 * 表单提交
 * @param values
 */
const handleSubmit = async (values: any) => {
  try {
    const res = await loginApi(values)
    // 登录成功
    if (res.data.code === 0) {
      await userStore.fetchLoginUserInfo()
      message.success('登录成功')
      // 跳转到首页
      await router.replace('/')
    } else {
      message.error(res.data.message)
    }
  } catch (e: any) {
    message.error('登录失败，' + e.message)
  }
}
</script>
<style scoped>
#user-login {
  max-width: 360px;
  margin: 0 auto;

  .title {
    text-align: center;
    margin-bottom: 16px;
  }

  .description {
    color: #bbb;
    text-align: center;
    margin-bottom: 16px;
  }

  .tips {
    color: #bbb;
    font-size: 13px;
    text-align: right;
    margin-bottom: 16px;
  }
}
</style>
